public class BinarySearchTree {
    //二叉搜索树
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }
    }
    public TreeNode root;
    //查找
    public TreeNode search(int key){
        TreeNode cur=root;
        while (cur!=null){
            if(cur.val>key){
                cur=cur.right;
            }else if(cur.val==key){
                return cur;
            }else {
                cur=cur.left;
            }
        }
        return null;
    }
    //插入
public void insert(int key){
        if(root==null){
            root=new TreeNode(key);
            return;
        }
        TreeNode node=new TreeNode(key);
        TreeNode parent=null;
        TreeNode cur=root;
        while (cur!=null){
            if(key>cur.val){
                parent=cur;
                cur=cur.right;
            }else if(key<cur.val){
                parent=cur;
                cur=cur.left;
            }else {
                return;
            }
        }
        if(parent.val>key){
            parent.left=node;
        }else{
            parent.right=node;
    }
}
    //删除
    public void remove(int key){
        TreeNode parent=null;
        TreeNode cur=root;
        while (cur!=null){
            if(key>cur.val){
                parent=cur;
                cur=cur.right;
            }else if(key<cur.val){
                parent=cur;
                cur=cur.left;
            }else {
                removeNode(parent,cur);
                return;
            }
        }
    }
    public void removeNode(TreeNode tp,TreeNode t){
        //左子树为null
        if(t.left==null){
            if(t==root){
                root=t.right;
            }else if(t==tp.left){
                tp.left=t.right;
            }else{
                tp.right=t.right;
            }
        }else if(t.right==null){  //右子树为空
            if(t==root){
                root=t.left;
            }else if(t==tp.left){
                tp.left=t.left;
            }else{
                tp.right=t.left;
            }
        }else{
            TreeNode ttp=t;
            TreeNode tt=t.right;
            while (tt.left!=null){
                ttp=tt;
                tt=tt.left;
            }
            t.val= tt.val;
            if(ttp.left==t){
                ttp.left=tt.right;
            }else {
                ttp.right=tt.right;
            }
        }
    }
}
